package org.example.springboot01.utils;



import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.Claim;
import com.auth0.jwt.interfaces.DecodedJWT;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

public class JwtUtils {
    private static final String SECRET = "qly";
    // 过期时间（1小时）
    private static final long EXPIRATION = 1000 * 60 * 60;
    // 签发者
    private static final String ISSUER = "springboot-system";

    private JwtUtils() {} // 私有构造防止实例化

    public static String getToken(Map<String, Object> claims) {
        return JWT.create()
                .withIssuer(ISSUER) // 签发者
                .withExpiresAt(new Date(System.currentTimeMillis() + EXPIRATION)) // 过期时间
                .withPayload(claims) // 装载自定义claims
                .sign(Algorithm.HMAC256(SECRET)); // 签名
    }
    // ：添加验证方法
    public static DecodedJWT verify(String token) {
        return JWT.require(Algorithm.HMAC256(SECRET))
                .withIssuer(ISSUER)
                .build()
                .verify(token);
    }

    public static Map<String, Object> parseToken(String token) {
        DecodedJWT jwt = verify(token);  // 复用验证逻辑
        Map<String, Claim> jwtClaims = jwt.getClaims();

        // 将Claim对象转换为普通值对象
        Map<String, Object> claims = new HashMap<>();
        jwtClaims.forEach((key, claim) -> {
            // 根据claim类型转换值
            Object value = claim.as(Object.class);
            claims.put(key, value);
        });
        return claims;
    }

}
